/*
输入一个英文句子， 翻转句子中单词的顺序， 但单词内字符的顺序不变。 句子中单词以空格符隔开。为简单起见，标点符号和普通字母一样处理。 

例如输入―  I am a student.，则输出―  student. a am I。 

分析：翻转―I am a student.中所有字符得到―.tneduts a ma I，再翻转每个单词中字符的顺序得到―students.aamI

*/
#include <stdio.h>
#include <stdlib.h>
#define MAX 100

//
void revert(char *str, int begin, int end)
{
    int len = end - begin + 1;
    int i;
    char tmp;

    //以中间单词为中心逆转单词
    for (i = 0; i < len / 2; i++)
    {
        tmp = str[begin + i];
        str[begin + i] = str[begin + len - i - 1];
        str[begin + len - i - 1] = tmp;
    }
}

//
char *str_process(char *str)
{
    int len = strlen(str);
    revert(str, 0, len - 1); //句子反转
    printf("after revert the str is %s\n", str);
    //char* tmp = str;
    int start = 0; //指向单词的开始
    int end = 0;   //指向单词的结束
    while (str[end] != '\0')
    {
        system("PAUSE");
        printf("start is %c, end is %c\n", str[start], str[end]);

        //处理每个单词
        if (str[start] == ' ') //跳过空格
        {
            start++;
            end++;
            continue;
        }
        else if (str[end + 1] == ' ') //一个单词倒转
        {
            revert(str, start, end);
            end++;
            start = end;
        }
        else if (str[end + 1] == '\0')
        {
            revert(str, start, end);
            end++;
        }
        else
            end++;
    }
    return str;
}
int main(int argc, char *argv[])
{
    char *str = (char *)malloc(MAX);
    sprintf(str, "%s", "We love china");
    printf("str is %s\n", str);
    printf("after process the str is %s\n", str_process(str));
    system("PAUSE");
    return 0;
}
